#pragma once
#include <iostream>
#include <sys/select.h>
#include <functional>
#include <poll.h>
#include "sock.hpp"
#include "err.hpp"

namespace pollServer
{
    using func_t = std::function<std::string(const std::string &)>;
    class PollServer
    {
        const static int defaultport = 8080;
        const static int default_val = -1; // fd数组的默认值
        const static int num = 2048;

    public:
        PollServer(func_t cb, int port = defaultport) : _port(port), _listensock(-1), _pollArray(nullptr), _cb(cb)
        {
        }
        ~PollServer()
        {
            close(_listensock);
            delete[] _pollArray;
        }

        void ResetItem(int i)
        {
            _pollArray[i].fd = default_val;
            _pollArray[i].events = 0;
            _pollArray[i].revents = 0;
        }
        void initServer()
        {

            // 1.创建套接字
            _listensock = Sock::Socket();

            // 1.5取消time_wait状态的绑定冷却时间
            int opt = 1;
            setsockopt(_listensock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));

            // 2.绑定ip和端口
            Sock::Bind(_listensock, _port);

            // 3.设置监听状态
            Sock::Listen(_listensock);

            // 4.初始化poll数组
            _pollArray = new struct pollfd[num];
            for (int i = 0; i < num; ++i)
            {
                ResetItem(i);
            }

            _pollArray[0].fd = _listensock;
            _pollArray[0].events = POLLIN;
            _pollArray[0].revents = 0;
        }

        void Accepter()
        {

            // 处理监听事件
            std::string clientip;
            uint16_t clientport;
            // 不会等待，直接获取连接
            int sock = Sock::Accept(_listensock, &clientip, &clientport);
            if (sock >= 0)
            {
                logMessage(NORMAL, "accept a new client, clientip: %s, clientport: %d", clientip.c_str(), clientport);
            }
            int i = 0;
            for (; i < num; ++i)
            {
                if (_pollArray[i].fd == default_val)
                {
                    _pollArray[i].fd = sock;
                    _pollArray[i].events = POLLIN;
                    break;
                }
            }
            if (i == num) // 说明服务器压力太大，丢弃新的连接套接字，等服务器缓存过来后，需要重新连接
            {
                close(sock);
                return;
            }
            Print();
        }

        // 处理客户端连接请求
        void Recver(int fdIndex)
        {
            char buffer[1024];
            // 1.接受请求
            ssize_t n = recv(_pollArray[fdIndex].fd, buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
            }
            else if (0 == n)
            {
                close(_pollArray[fdIndex].fd);
                ResetItem(fdIndex);
                logMessage(NORMAL, "client quit");
                return;
            }
            else
            {
                close(_pollArray[fdIndex].fd);
                ResetItem(fdIndex);
                logMessage(ERROR, "client quit err string: %s", strerror(errno));
                return;
            }

            std::cout << "echo# " << buffer << std::endl;

            // 暂时不考虑发送的等待问题     ----bug-----   select处理起来比较麻烦
            std::string response;
            response = _cb(buffer);
            write(_pollArray[fdIndex].fd, response.c_str(), response.size());
        }

        // 处理select监视成功后的新任务
        void HandlerEvent()
        {
            for (int i = 0; i < num; ++i)
            {
                if (_pollArray[i].fd == default_val)
                    continue;
                if (!(_pollArray[i].events & POLLIN))
                    continue;

                if (_pollArray[i].fd == _listensock && (_pollArray[i].revents & POLLIN))
                {
                    Accepter();
                }
                else if (_pollArray[i].revents & POLLIN)
                {
                    Recver(i);
                }
            }
        }
        void Print()
        {
            std::cout << "fd list: ";
            for (int i = 0; i < num; ++i)
            {
                if (_pollArray[i].fd == default_val)
                    continue;
                else
                    std::cout << " " << _pollArray[i].fd << " ";
            }
            std::cout << std::endl;
        }
        void start()
        {

            while (1)
            {
                int timeout = 1000;
                int n = poll(_pollArray, num, -1);
                // 一般我们使用select，需要程序员自定义一个文件描述符数组来维护select监控的数组,select技术的缺点
                switch (n)
                {
                case 0:
                    logMessage(NORMAL, "timeout....");
                    break;
                case -1:
                    // 调用失败了
                    logMessage(ERROR, "select err, code: %d  errstr: %s", errno, strerror(errno));
                    break;
                default:
                    // 说明事件就绪了
                    logMessage(NORMAL, "have a new message");
                    //HandlerEvent();
                    break;
                }
            }
        }

    private:
        int _listensock;
        int _port;
        func_t _cb; // 回调方法：由上层提供的业务逻辑

        struct pollfd *_pollArray;
    };
}